package action

import (
	"encoding/json"
	"github.com/kataras/iris/v12/context"
	"github.com/kataras/iris/v12/mvc"
)

type JsonResult struct {
	Code int
	Msg  string
	Data any
}

// Dispatch writes the response result to the context's response writer.
func (r *JsonResult) Dispatch(ctx *context.Context) {
	ctx.ResponseWriter().WriteHeader(200)
	ctx.ResponseWriter().Header().Set("Content-Type", "application/json")
	result := make(map[string]any)
	result["code"] = r.Code
	result["msg"] = r.Msg
	if r.Data != nil {
		result["data"] = r.Data
	}
	_ = json.NewEncoder(ctx.ResponseWriter()).Encode(result)
}

func NewJsonResult(code int, msg string, data any) mvc.Result {
	return &JsonResult{Data: data, Code: code, Msg: msg}
}

type JsonData struct {
	Data any
}

// Dispatch writes the response result to the context's response writer.
func (r *JsonData) Dispatch(ctx *context.Context) {
	ctx.ResponseWriter().WriteHeader(200)
	ctx.ResponseWriter().Header().Set("Content-Type", "application/json")
	result := make(map[string]any)
	result["code"] = 0
	result["msg"] = "ok"
	if r.Data != nil {
		result["data"] = r.Data
	}
	_ = json.NewEncoder(ctx.ResponseWriter()).Encode(result)
}

func Data(data any) mvc.Result {
	return &JsonData{Data: data}
}

func ServerError() mvc.Result {
	return &JsonResult{Data: nil, Code: 500, Msg: "服务器出现错误"}
}

func ParamError() mvc.Result {
	return &JsonResult{Data: nil, Code: 600, Msg: "参数错误"}
}

func Error(msg string) mvc.Result {
	return &JsonResult{Data: nil, Code: 500, Msg: msg}
}

func AdminError() mvc.Result {
	return &JsonResult{Data: nil, Code: 601, Msg: "不允许的操作"}
}

func OK() mvc.Result {
	return &JsonResult{Data: nil, Code: 0, Msg: "ok"}
}
